<template>
  <!--文章收藏按钮-->
  <van-button :icon="value ? 'star' : 'star-o'" :class="{collected: value}" :loading="loading" @click="onCollect" />
</template>

<script>
import { addCollect, deleteCollect } from '@/api/article'
export default {
  name: 'CollectArticle',
  components: {},
  data () {
    return {
      loading: false
    }
  },
  props: {
    value: {
      required: true,
      type: Boolean
    },
    articleId: {
      required: true,
      type: [Number, String, Object]
    }
  },
  methods: {
    async onCollect () {
      this.loading = true
      try {
        if (this.value) {
          // 已收藏，取消收藏
          await deleteCollect(this.articleId)
        } else {
          // 已收藏，取消收藏
          await addCollect(this.articleId)
        }
        // 更新视图
        this.$emit('input', !this.value)
        this.$toast.success(this.value ? '收藏成功' : '取消收藏')
      } catch (err) {
        // this.$toast.fail('操作失败，请重试！')
        let message = '操作失败，请稍后重试！'
        if (err.response && err.response.status === 401) {
          message = '请登录后再收藏！'
          this.$router.push('/login')
        }
        this.$toast(message)
      }
      this.loading = true
    }
  }
}
</script>

<style scoped lang="less">
.van-button--default{
  border: none;
}
.collected{
  .van-icon{
    color: #ee0a24;
  }
}
</style>
